/*
 * TDS PEC 4
 * Grupo 3H2M
 * 
 * El paquete <code>edu.uoc.tds.pec4.estadisticas</code> contiene la implementación de
 * todas las clases necesarias para la interfaz gráfica del ss de estadísticas
 *
 */
package edu.uoc.tds.pec4.estadisticas;

import edu.uoc.tds.pec4.beans.CiudadDTO;
import edu.uoc.tds.pec4.beans.RankingLocalizacionDTO;
import edu.uoc.tds.pec4.common.components.TablaUI;
import edu.uoc.tds.pec4.common.util.Cabecera;
import edu.uoc.tds.pec4.common.util.Constantes;
import edu.uoc.tds.pec4.common.util.TDSLanguageUtils;
import edu.uoc.tds.pec4.common.util.UtilidadesGUI;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/**
 *
 * @author Isabel Guerra Monclova
 */
public class DialogResultadoRankingLocalizaciones extends javax.swing.JDialog {
    
    private List<RankingLocalizacionDTO> listado = null;
    
    //Contendra el listado obtenido, en formato grid
    private TablaUI tablaListado = null;
    private JScrollPane jScrollPane = null;
    
    private Boolean agrupadoMeses;

    /** Creates new form JDResultadoRankingAulas */
    public DialogResultadoRankingLocalizaciones(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        //setBounds (10,10, 900,390);
        //setResizable(false);
        initComponents();
        inicializarComponentes();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        localizacion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        fechaInicio = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        fechaFin = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        agrupadoPor = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        top = new javax.swing.JTextField();
        panelListado = new javax.swing.JPanel();
        cerrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(TDSLanguageUtils.getMessage("estadistica.resultado")+" "+TDSLanguageUtils.getMessage("estadistica.ranking.localizaciones.titulo"));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("resultados.filtros.seleccionados")));

        jLabel1.setText(TDSLanguageUtils.getMessage("aulas.consulta.solicitudes.localizacion"));

        localizacion.setEnabled(false);

        jLabel3.setText(TDSLanguageUtils.getMessage("estadistica.ranking.fecha.inicio"));

        fechaInicio.setEnabled(false);

        jLabel4.setText(TDSLanguageUtils.getMessage("estadistica.ranking.fecha.fin"));

        fechaFin.setEnabled(false);
        fechaFin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fechaFinActionPerformed(evt);
            }
        });

        jLabel5.setText(TDSLanguageUtils.getMessage("estadistica.ranking.agrupar"));

        agrupadoPor.setEnabled(false);

        jLabel6.setText(TDSLanguageUtils.getMessage("estadistica.ranking.top"));

        top.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(67, 67, 67)
                                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(localizacion, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fechaFin))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(agrupadoPor, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(top)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(localizacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5)
                    .addComponent(agrupadoPor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6)
                    .addComponent(top, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelListado.setBorder(javax.swing.BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("estadistica.ranking.localizaciones.titulo")));

        javax.swing.GroupLayout panelListadoLayout = new javax.swing.GroupLayout(panelListado);
        panelListado.setLayout(panelListadoLayout);
        panelListadoLayout.setHorizontalGroup(
            panelListadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 732, Short.MAX_VALUE)
        );
        panelListadoLayout.setVerticalGroup(
            panelListadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 211, Short.MAX_VALUE)
        );

        cerrar.setText(TDSLanguageUtils.getMessage("boton.cerrar"));
        cerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cerrar)
                    .addComponent(panelListado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelListado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cerrar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void fechaFinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fechaFinActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_fechaFinActionPerformed

private void cerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cerrarActionPerformed
    dispose();
}//GEN-LAST:event_cerrarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField agrupadoPor;
    private javax.swing.JButton cerrar;
    private javax.swing.JTextField fechaFin;
    private javax.swing.JTextField fechaInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField localizacion;
    private javax.swing.JPanel panelListado;
    private javax.swing.JTextField top;
    // End of variables declaration//GEN-END:variables

    public void setFechaFin(JTextField fechaFin) {
        this.fechaFin.setText(fechaFin.getText());
    }

    public void setFechaInicio(JTextField fechaInicio) {
        this.fechaInicio.setText(fechaInicio.getText());
    }

    public void setLocalizacion(List<CiudadDTO> ciudades) {
        String lista = "";
        int size = 1;
        for(CiudadDTO ciu : ciudades) {
            if (size == 1) {
                lista = ciu.getNomCiudad();
            } else {
                lista = lista + ", " + ciu.getNomCiudad();
            }
            size ++;
        }
        
        this.localizacion.setText(lista);
    }

    public void setTop(String texto) {
        this.top.setText(texto);
    }

    public List<RankingLocalizacionDTO> getListado() {
        return listado;
    }

    public void setListado(List<RankingLocalizacionDTO> listado) {
        this.listado = listado;
        //Montar tabla de resultados
        
        if(!listado.isEmpty()) {
            panelListado.add(getJScrollPane(), null);
            tablaListado.setFilas(getFilasTabla(listado));
            tablaListado.refrescarFilas();
        }
    }
    
     /**
     * A partir de una lista de objetos, devuelve listas de listas de objetos para
     * que se puedan mostrar en una tabla
     *
     * @return javax.swing.JTable
     */
    private List<List> getFilasTabla(List<RankingLocalizacionDTO> vCv) {
        List<List> rankings = new ArrayList<List>();

        try {
            
            //Si está agrupado por meses mostramos el mes
            List<String> vMes = null;
            if(agrupadoMeses) {
                vMes = new ArrayList<String>();
            }
            List<String> vCiudad = new ArrayList<String>();
            List<String> vGrado = new ArrayList<String>();
            List<Integer> vReserva = new ArrayList<Integer>();
            List<String> vMedia = new ArrayList<String>();
            List<Integer> vAsistentes = new ArrayList<Integer>();
            List<String> vMediaAsis = new ArrayList<String>();
            List<String> vFacturacion = new ArrayList<String>();
            for (RankingLocalizacionDTO cv : vCv) {
                if(agrupadoMeses) { 
                    vMes.add(cv.getMes());
                }
                vCiudad.add(cv.getCiudad());
                vGrado.add(UtilidadesGUI.obtenerPorcentaje(cv.getGradoReserva()));
                vReserva.add(cv.getReservas());
                vMedia.add(UtilidadesGUI.obtenerDecimal(cv.getMediaDiasReserva()));
                vAsistentes.add(cv.getAsistentes());
                vMediaAsis.add(UtilidadesGUI.obtenerDecimal(cv.getMediaAsistentes()));
                vFacturacion.add(UtilidadesGUI.obtenerImporte(cv.getFacturacion()));
            }
            if(agrupadoMeses) {
                rankings.add(vMes);
            }
            rankings.add(vCiudad);
            rankings.add(vGrado);
            rankings.add(vReserva);
            rankings.add(vMedia);
            rankings.add(vAsistentes);
            rankings.add(vMediaAsis);
            rankings.add(vFacturacion);
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                TDSLanguageUtils.getMessage("estadistica.error.filas") + Constantes.SL +
                e.getMessage(), TDSLanguageUtils.getMessage("estadistica.error"),
                JOptionPane.ERROR_MESSAGE);
        }

        return rankings;
    }

    public Boolean getAgrupadoMeses() {
        return agrupadoMeses;
    }

    public void setAgrupadoMeses(Boolean agrupadoMeses) {
        if(agrupadoMeses)
            this.agrupadoPor.setText(TDSLanguageUtils.getMessage("estadistica.ranking.agrupado.meses"));
        this.agrupadoMeses = agrupadoMeses;
    }

    private void inicializarComponentes() {
        //panelListado.add(getJScrollPane(), null);
        agrupadoMeses = Boolean.FALSE;
    }

    /**
     * Este método inicializa jScrollPane
     *
     * @return javax.swing.JScrollPane
     */
    private JScrollPane getJScrollPane() {
        if (jScrollPane == null) {
            jScrollPane = new JScrollPane();
            jScrollPane.setBounds(new Rectangle(10, 20, 710, 175));
            jScrollPane.setViewportView(getTablaListado());
        }
        return jScrollPane;
    }

    private Component getTablaListado() {
        if (tablaListado == null) {
            tablaListado = new TablaUI(getCabecerasTabla(), getFilasTabla(new ArrayList<RankingLocalizacionDTO>()));
            tablaListado.setLocation(new Point(0, 0));

            // PENDIENTE: Captura del evento sobre la columna para ordenar mediante SQL
            tablaListado.getTableHeader().addMouseListener(new MouseAdapter() {
                
                  public void mouseClicked(MouseEvent mouseEvent) {
                    int index = tablaListado.convertColumnIndexToModel(tablaListado.columnAtPoint(mouseEvent.getPoint()));
                    if (index >= 0) {
                      System.out.println("Click en columna " + index + " " + tablaListado.getModel().getColumnName(index));
                    }
                  };
                });            
        }
        return tablaListado;
    }

    private List<Cabecera> getCabecerasTabla() {
       // La Cabecera indica el nombre de columna y tamaño
        List<Cabecera> vCabecera = new ArrayList<Cabecera>();
        
        // Recordar: Cabecera (titulo, anchoColumna)
        if (agrupadoMeses) {
            vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.mes"),50));
        }

        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.ciudad"),80));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.grado"),80));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.reservas"),90));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.media.diasreserva"),80));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.asistentes"),80));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.media.asistentes"),90));
        vCabecera.add(new
                Cabecera(TDSLanguageUtils.getMessage("estadistica.ranking.tabla.facturacion"),90));

        return vCabecera;
    }
}
